﻿using Domain.Entities;
using Domain.ValueObjects;
using Infrastructure.Data.ValueConverter;
using Microsoft.EntityFrameworkCore;
using Shared.Domain.Abstructs;

namespace Infrastructure.Data.Contexts
{
    public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
    {
        

        internal DbSet<User> Users { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //直接配置
            modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);


        }

        protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
        {
            configurationBuilder.Properties<PhoneNumber>()
                .HaveConversion<PhoneNumberToStringConverter>();

            configurationBuilder.Properties<NickName>()
                .HaveConversion<NickNameToStringConverter>();

            configurationBuilder.Properties<RealName>()
                .HaveConversion<RealNameToStringConverter>();
        }

        public override int SaveChanges(bool acceptAllChangesOnSuccess)
        {
            SetTimestamps();
            return base.SaveChanges(acceptAllChangesOnSuccess);
        }

        public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
        {
            SetTimestamps();
            return base.SaveChangesAsync(cancellationToken);
        }

        private void SetTimestamps()
        {
            var now = DateTime.UtcNow;

            var entries = ChangeTracker.Entries()
                .Where(e => e.Entity is BaseEntity<Guid> &&
                           (e.State == EntityState.Added || e.State == EntityState.Modified));

            foreach (var entry in entries)
            {
                //修改时设置更新时间
                entry.Property(nameof(BaseEntity<Guid>.UpdateTime)).CurrentValue = now;
                
                //新增时设置创建时间
                if (entry.State == EntityState.Added)
                {
                    entry.Property(nameof(BaseEntity<Guid>.CreateTime)).CurrentValue = now;
                }
            }
        }
    }
}